package com.earogya.logic.patient_details;

import java.util.Calendar;
import java.util.List;
import org.apache.struts.ehr.patient_details.model.*;

import com.earogya.Constants;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.*;
import ca.uhn.hl7v2.model.v251.message.QRY_A19;

/***
 * 
 * Create QRY A19 message based on the user input
 * Used to query patient details from the database
 * 
 * @author Ureka
 *
 */

public class CreateQRYA19 {
	private QRY_A19 qry;
	private PatientDetails patientDetails;
	
	public CreateQRYA19(PatientDetails patientDetails){
		this.qry=new QRY_A19();
		this.patientDetails=patientDetails;
	}
	
	
	/**
	 * 
	 * Create the message
	 * 
	 * @param sendingFacility
	 * @return
	 * @throws HL7Exception
	 */
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addSearchDetails();
		return qry.getMessage().encode();
	}
	
/**
 * Create the message header
 * 
 * @param sendingFacility
 * @throws DataTypeException
 */
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		qry.getMSH().getFieldSeparator().setValue("|");
		qry.getMSH().getEncodingCharacters().setValue("^~\\&");
		qry.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		qry.getMSH().getMessageType().getMsg1_MessageCode().setValue("QRY");
		qry.getMSH().getMessageType().getTriggerEvent().setValue("A19");
		qry.getMSH().getSendingApplication().getUniversalID().setValue(Constants.SENDING_APPLICATION);
		qry.getMSH().getVersionID().getVersionID().setValue(Constants.HL7_VERSION);
		qry.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		qry.getMSH().getReceivingApplication().getUniversalID().setValue(Constants.RECEIVING_APPLICATION_PATIENT_DETAILS_SERVICE);
		qry.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	/**
	 * 
	 * Add the query details to the message
	 * 
	 * @throws DataTypeException
	 */
	private void addSearchDetails() throws DataTypeException{
		Patient patient=patientDetails.getPatient();
		
		qry.getQRD().getWhatSubjectFilter(0).getIdentifier().setValue(Constants.DEM);
		XCN who=qry.getQRD().getWhoSubjectFilter(0);
		if(patient.getPatientId()==""){}
		else{
		who.getIDNumber().setValue(String.valueOf(patient.getPatientId()));
		}
		who.getGivenName().setValue(patient.getGivenName());
		who.getFamilyName().getSurname().setValue(patient.getFamilyName());
		who.getIdentifierCheckDigit().setValue(patient.getNicNo());
	}
}
